/**
 * 
 */
package gemini.basic.batch;

import java.util.List;

import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.SchedulerException;
import org.quartz.TriggerListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Listener for all triggers.
 * 
 */
public class GmnGlobalTriggerListener implements TriggerListener {

	private final Logger logger = LoggerFactory
			.getLogger(GmnGlobalTriggerListener.class);

	@Override
	public String getName() {
		return "GmnGlobalTriggerListener";
	}

	@Override
	public void triggerFired(org.quartz.Trigger trigger,
			JobExecutionContext context) {
		logger.debug("{} fired.....!!!!!!", trigger.getName());
	}

	@Override
	public boolean vetoJobExecution(org.quartz.Trigger trigger,
			JobExecutionContext context) {
		JobDetail job = context.getJobDetail();
		String jobName = job.getName();

		// get list of executing jobs
		try {
			List<JobExecutionContext> executingJobList = (List<JobExecutionContext>) context
					.getScheduler().getCurrentlyExecutingJobs();
			if (executingJobList.isEmpty()) {
				return false;
			}

			for (JobExecutionContext executingContext : executingJobList) {
				JobDetail executingJob = executingContext.getJobDetail();
				String executingJobName = executingJob.getName();
				// check if there is any same job running, compare exactly the
				// job name
				if (executingJobName.equals(jobName)) {
					// the same job is running, cancel the job that to be
					// executed
					logger.warn(
							"{} execution is vetoed because the same job is running.",
							jobName);
					return true;
				}
			}

		} catch (SchedulerException e) {
			logger.error("{} execution is vetoed because of error:{}", jobName,
					e);
			return true;
		}

		return false;
	}

	@Override
	public void triggerMisfired(org.quartz.Trigger trigger) {
		logger.debug("{} missed fire....!!!", trigger.getName());
	}

	@Override
	public void triggerComplete(org.quartz.Trigger trigger,
			JobExecutionContext context, int triggerInstructionCode) {
		logger.debug("{} completed....!!!", trigger.getName());
	}

}
